import SwiftUI
import Kingfisher

struct FoodStoreItemView: View {
    
    var model: FoodStoreItemModel
    
    @Environment(Router.self) private var router
    
    private var showStoreLoacal: Bool {
        !model.distance.isEmpty
    }
    
    private var distance: String {
        guard let doubleDistance = Double(model.distance)  else { return "" }
        if doubleDistance > 1000 {
            return String(format: "%.2f", doubleDistance / 1000) + "km"
        } else {
            guard let intDistance = Int(model.distance) else { return ""}
            return "\(intDistance)m"
        }
    }
    
    var body: some View {
        VStack(spacing: 12.0) {
            HStack(spacing: 8.0) {
                // 店铺图片
                KFImage(URL(string: model.storeImgUrl))
                    .placeholder({
                        WebImageLoadingView()
                    })
                    .onFailureImage(.iconPlaceholderFood)
                    .resizable()
                    .frame(width: 48.0, height: 48.0)
                    .clipShape(RoundedRectangle(cornerRadius: 8.0))
                // 店铺信息
                VStack(alignment: .leading, spacing: 8.0) {
                    // 名称 和 入驻认证标签
                    HStack(spacing: 2.0) {
                        Text(model.title)
                            .font(.alibabaPuHuiTi(size: 18.0, weight: .semiBold))
                            .foregroundStyle(.fs020000)
                            .lineLimit(1)
                        if model.isEntry {
                            EntryLabelView()
                        }
                    }
                    // 评分 和 地点
                    HStack(spacing: 0) {
                        FoodPointsView(points: model.points, num: model.pointsPeopleNum)
                        Spacer()
                        if showStoreLoacal {
                            Text("商圈地点·\(distance)")
                                .font(.alibabaPuHuiTi(size: 14.0, weight: .regular))
                                .lineLimit(1)
                                .foregroundStyle(.fs575958)
                        }
                    }
                }
            }
            .onTapGesture {
                Log.debug("点击店铺: \(model.title)")
                router.push(AppRoute.storeDetailView(storeId: model.id))
            }
            // 美食
            HStack(spacing: 8.0) {
                ForEach(model.foods, id: \.id) { food in
                    FoodItemView(model: food)
                        .onTapGesture {
                            Log.debug("点击美食: \(food.title)")
                            router.push(AppRoute.foodDetailView(storeId: food.id))
                        }
                }
            }
        }
        .padding(12.0)
        .background(.fsFFFFFF)
        .clipShape(
            RoundedRectangle(cornerRadius: 16.0)
        )
    }
}
